<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Payment extends FrontEndController {
    public function __construct() {
        parent::__construct();
        $this->lang->load('error', 'vietnamese');
        $this->load->model('repo/product_model', 'product_model');
    }

    public function index() {
        $this->load->model('repo/user_model', 'user_model');
        $obj_user = new User_Entity();
        $user_id  = $this->session->userdata('user_id');
        if($user_id !== false){
            $obj_user = $this->user_model->getUserById($user_id, false, 'a.id, a.full_name, a.email, a.phone, a.address');
        }
        $aReturn = array(
            'no-sidebar' => true,
            'pageTitle'  => 'Giỏ hàng - Thanh toán',
            'cart'       => $this->cart->contents(),
            'obj_user'   => $obj_user
            );
        $this->renderView('pages/payment', $aReturn);
    }

    public function directAddToCart() {
        $item = $this->input->post('cart', true);
        if ($item != null && isset($item['id']) && $item['id'] != '') {
            $oDetails = $this->product_model->getProductDetailInfo($item['id']);
            if ($oDetails != null) {
                $aItem['id']    = $item['id'];
                $aItem['qty']   = $item['qty'];
                $aItem['price'] = $item['price'];
                $aItem['name']  = $oDetails->title;
                $aItem['options']['slug']              = $oDetails->slug;
                $aItem['options']['image']             = $oDetails->getImage();
                $aItem['options']['code']              = $oDetails->getCode();
                $aItem['options']['shop_id']           = $oDetails->shop_id;
                $aItem['options']['shop_title']        = $oDetails->shop_title;
                $aItem['options']['shop_slug']         = $oDetails->shop_slug;
                $aItem['options']['shop_image_folder'] = $oDetails->shop_image_folder;
                $aItem['options']['email']             = $oDetails->shop_email;
                $this->cart->insert($aItem);

                $url = $this->input->get('ref');
                if($url!=false){
                    redirect(page_url('gio-hang', array('ref'=>$url)));
                } else {
                    redirect(page_url('gio-hang'));
                }
            } else {
                die('Invalid data');
            }
        } else {
            die('Invalid data');
        }
    }

    public function addToCart() {
        $result = -1;
        $item = $this->input->post('cart', true);
        if ($item != null && isset($item['id']) && $item['id'] != '') {
            $oDetails = $this->product_model->getProductDetailInfo($item['id']);
            if ($oDetails != null) {
                $aItem['id']    = $item['id'];
                $aItem['qty']   = $item['qty'];
                $aItem['price'] = $item['price'];
                $aItem['name']  = $oDetails->title;
                $aItem['options']['slug']              = $oDetails->slug;
                $aItem['options']['image']             = $oDetails->getImage();
                $aItem['options']['code']              = $oDetails->getCode();
                $aItem['options']['shop_id']           = $oDetails->shop_id;
                $aItem['options']['shop_title']        = $oDetails->shop_title;
                $aItem['options']['shop_slug']         = $oDetails->shop_slug;
                $aItem['options']['shop_image_folder'] = $oDetails->shop_image_folder;
                $aItem['options']['email']             = $oDetails->shop_email;
                $this->cart->insert($aItem);
                $result = 200;
            }
        }
        echo $result;
    }

    public function addToCartFromList() {
        $result = -1;
        $id = $this->input->post('id', true);
        if ($id != null && $id != '') {
            $oDetails = $this->product_model->getProductDetailInfo($id);
            if ($oDetails != null) {
                $aItem['id']    = $oDetails->product_id;
                $aItem['qty']   = 1;
                $aItem['price'] = $oDetails->getPriceNew();
                $aItem['name']  = $oDetails->title;
                $aItem['options']['slug']              = $oDetails->slug;
                $aItem['options']['image']             = $oDetails->getImage();
                $aItem['options']['code']              = $oDetails->getCode();
                $aItem['options']['shop_id']           = $oDetails->shop_id;
                $aItem['options']['shop_title']        = $oDetails->shop_title;
                $aItem['options']['shop_slug']         = $oDetails->shop_slug;
                $aItem['options']['shop_image_folder'] = $oDetails->shop_image_folder;
                $aItem['options']['email']             = $oDetails->shop_email;
                $rowid = $this->cart->insert($aItem);
                $result = 200;
            }
        }
        echo $result;
        die();
    }

    public function deleteCartItem() {
        $result = -1;
        $rowId = $this->input->post('item', true);
        if ($rowId != null && $rowId != '' && $this->cart->has_options($rowId)) {
            $data = array('rowid' => $rowId, 'qty' => 0);
            $this->cart->update($data);
            $result = 200;
        }
        echo $result;
    }

    public function updateCartItem() {
        $subtotal = 0;
        $rowId = $this->input->post('item', true);
        if ($rowId != null && $rowId != '' && $this->cart->has_options($rowId)) {
            $qty = $this->input->post('quantity', true);
            if (is_numeric($qty) && $qty > 0) {
                $data = array('rowid' => $rowId, 'qty' => $qty);
                $this->cart->update($data);
                $p = $this->cart->contents();
                $subtotal = $p[$rowId]['subtotal'];
            }
        }
        echo $subtotal;
    }

    public function countCartItems() {
        echo $this->cart->total_items();
        die();
    }

    public function totalResult() {
        echo $this->renderJSON(array('total_items' => $this->cart->total_items(), 'total_price' => $this->cart->total()));
    }

    public function billing() {
        $aResult = array();
        $this->lang->load('error', 'vietnamese');
        $this->lang->load('form_validation', 'vietnamese');
        $this->load->library('form_validation');
        $order = $this->input->post('order', true);
        $this->form_validation->set_rules('order[name]',    'lang:order_name_invalid',    'trim|required|max_length[30]|xss_clean');
        $this->form_validation->set_rules('order[email]',   'lang:order_email_invalid',   'trim|required|valid_email|xss_clean');
        $this->form_validation->set_rules('order[phone]',   'lang:order_phone_invalid',   'trim|required|max_length[12]|min_length[10]|integer|xss_clean');
        $this->form_validation->set_rules('order[address]', 'lang:order_address_invalid', 'trim|required|max_length[1000]|xss_clean');
        if(isset($order['order_info_same']) && $order['order_info_same']==1){
            $this->form_validation->set_rules('order[receiver_name]',    'lang:order_receiver_name_invalid',    'trim|required|max_length[30]|xss_clean');
            $this->form_validation->set_rules('order[receiver_email]',   'lang:order_receiver_email_invalid',   'trim|required|valid_email|xss_clean');
            $this->form_validation->set_rules('order[receiver_phone]',   'lang:order_receiver_phone_invalid',   'trim|required|max_length[12]|min_length[10]|integer|xss_clean');
            $this->form_validation->set_rules('order[receiver_address]', 'lang:order_receiver_address_invalid', 'trim|required|max_length[150]|xss_clean');
        } else {
            $order['receiver_name']    = NULL;
            $order['receiver_email']   = NULL;
            $order['receiver_phone']   = NULL;
            $order['receiver_address'] = NULL;
        }
        $this->form_validation->set_rules('order[note]',    'lang:order_note_invalid',    'trim|max_length[1000]|xss_clean');
        $this->form_validation->set_error_delimiters('<li>', '</li>');
        $is_valid = $this->form_validation->run();

        $aLiErrows = '';
        if(!$is_valid){
            $aLiErrows = validation_errors();
        }
        $cart = $this->cart->contents();
        if(count($cart)==0){
            $aLiErrows = "<li>" . $this->lang->line('order_blank') . '</li>' . $aLiErrows;
        }
        if ($aLiErrows!='') {
            $aResult = array(
                'code'  => 0,
                'title' => $this->lang->line('order_fail'),
                'text'  => '<ul>' . $aLiErrows . '</ul>',
                );
            $this->renderJSON($aResult);
            return;
        }

        $aShops = array();
        $aShopsTitle = array();
        if(isset($order['user']) && $order['user']!=''){
            $order['user'] = $this->encrypt->decode($order['user']);
            if($order['user']!=false){
                $order['user_id'] = $order['user'];
                unset($order['user']);
            }
        }

        foreach ($cart as $item) {
            $shop_id = $item['options']['shop_id'];
            if (!array_key_exists($shop_id, $aShops)) {
                $aShops[$shop_id] = array();
            }
            if (!in_array($item['options']['shop_title'], $aShopsTitle)) {
                array_push($aShopsTitle, $item['options']['shop_title']);
            }
            array_push($aShops[$shop_id], $item);
        }
        $this->load->model('repo/order_model', 'order_model');
        $result = $this->order_model->billing($aShops, $order, $cart);
        if ($result) {
            $aResult = array(
                'code' => 1,
                'text' => sprintf($this->lang->line('order_success'), implode(',', $aShopsTitle))
                );
            $this->cart->destroy();
        } else {
            $aResult = array(
                'code' => 0,
                'title'=> $this->lang->line('order_fail'),
                'text' => $this->lang->line('submit_shop_oder_fail')
                );
        }
        $this->renderJSON($aResult);
    }
}
?>